import json
import os

def convert_to_geojson_compact(input_json_path, output_geojson_path):
    """
    将特定格式的禁飞区JSON文件转换为标准的、紧凑的GeoJSON格式。
    """
    all_zones = []
    try:
        with open(input_json_path, 'r', encoding='utf-8') as f:
            try:
                all_zones = json.load(f)
                print("文件被识别为标准JSON数组。")
            except json.JSONDecodeError:
                print("文件不是标准JSON数组，尝试作为JSON Lines (NDJSON) 格式处理...")
                f.seek(0)
                for line in f:
                    line = line.strip()
                    if line:
                        try:
                            all_zones.append(json.loads(line))
                        except json.JSONDecodeError:
                            print(f"警告：跳过无效的JSON行: {line[:100]}...")
                            continue
                if not all_zones:
                    print(f"错误：无法从 {input_json_path} 解析任何有效的JSON数据。")
                    return
    except FileNotFoundError:
        print(f"错误：输入文件未找到 -> {input_json_path}")
        return
    except Exception as e:
        print(f"读取或解析文件时发生未知错误: {e}")
        return

    geojson_structure = {
        "type": "FeatureCollection",
        "features": []
    }

    if not isinstance(all_zones, list):
        all_zones = [all_zones]

    print(f"开始转换 {len(all_zones)} 个禁飞区...")

    for zone in all_zones:
        if not isinstance(zone, dict): continue

        parent_properties = zone.copy()
        parent_properties.pop('sub_areas', None)
        parent_properties.pop('polygon_points', None)

        if 'sub_areas' in zone and isinstance(zone.get('sub_areas'), list):
            for sub_area in zone['sub_areas']:
                if 'polygon_points' in sub_area and sub_area['polygon_points']:
                    feature_properties = parent_properties.copy()
                    feature_properties.update(sub_area)
                    feature_properties.pop('polygon_points', None)

                    geometry = {
                        "type": "Polygon",
                        "coordinates": sub_area['polygon_points']
                    }

                    feature = {
                        "type": "Feature",
                        "geometry": geometry,
                        "properties": feature_properties
                    }

                    geojson_structure['features'].append(feature)

    try:
        # 确保输出目录存在
        output_dir = os.path.dirname(output_geojson_path)
        if output_dir:
            os.makedirs(output_dir, exist_ok=True)

        with open(output_geojson_path, 'w', encoding='utf-8') as f:
            # 使用 separators=(',', ':') 来生成最紧凑的格式
            json.dump(
                geojson_structure,
                f,
                ensure_ascii=False,
                separators=(',', ':')
            )

        print("-" * 30)
        print("转换成功！")
        print(f"共生成 {len(geojson_structure['features'])} 个地理特征。")
        print(f"紧凑的GeoJSON文件已保存至: {os.path.abspath(output_geojson_path)}")
        print("-" * 30)

    except IOError as e:
        print(f"错误：无法写入文件 -> {output_geojson_path}. 原因: {e}")


# --- 使用说明 ---
if __name__ == "__main__":
    # 1. 指定输入文件路径
    input_file = os.path.join('data', 'DjiAreas4_CN.json')

    # 2. 指定输出文件路径
    output_file = os.path.join('data', 'DjiAreas4_CN.geojson')

    # 3. 运行脚本
    convert_to_geojson_compact(input_file, output_file)